<template>
  <div class="create-blog">
    <a-button 
      type="text" 
      class="back-btn"
      @click="$router.go(-1)"
    >
      < 返回
    </a-button>

    <h1>{{ isDiscussion ? '发表新讨论' : '发表新文章' }}</h1>

    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      layout="vertical"
    >
      <a-form-item label="标题" name="title">
        <a-input v-model:value="form.title" />
      </a-form-item>

      <a-card class="editor-container">
        <a-tabs v-model:activeKey="tab">
          <a-tab-pane key="edit" tab="编辑">
            <a-form-item label="内容" name="content">
              <a-textarea 
                v-model:value="form.content"
                :rows="20"
                style="min-height: 500px"
                @change="handleContentChange"
              />
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane key="preview" tab="预览">
            <div v-html="previewContent" class="preview-area"></div>
          </a-tab-pane>
        </a-tabs>
      </a-card>

      <div class="mt-4">
        <a-button 
          type="primary"
          @click="submitForm"
        >
          立即发表
        </a-button>
        <a-button 
          @click="saveDraft"
          style="margin-left: 10px"
        >
          保存草稿
        </a-button>
        <a-button 
          @click="resetForm"
          style="margin-left: 10px"
        >
          重置
        </a-button>
      </div>
    </a-form>
  </div>
</template>

<script>
import { useRoute } from 'vue-router'
import { useBlogStore } from '@/stores/blog'
import { useUserStore } from '@/stores/user'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import { message } from 'ant-design-vue'

const userStore = useUserStore()


export default {
  name: 'CreateBlogView',
  setup() {
    const md = new MarkdownIt({
      html: true,
      linkify: true,
      typographer: true,
      highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            return hljs.highlight(str, { language: lang }).value
          } catch (__) {}
        }
        return ''
      }
    })
    return { md }
  },
  computed: {
    previewContent() {  
      return this.md.render(this.form.content || '')
    },
    userStats() {
      return userStore.userStats
    }
  },
  data() {
    const router = useRoute()
    const draft = localStorage.getItem('blog_draft')
    return {
      valid: true,
      tab: 'edit',
      isDiscussion: router.query.type === 'discussion',
      problemId: router.query.problemId || null,
      form: {
        title: '',
        content: ''
      },
      rules: {
        title: [
          v => !!v || '请输入文章标题',
          v => (v && v.length >= 5 && v.length <= 50) || '长度在5到50个字符'
        ],
        content: [
          v => !!v || '请输入文章内容',
          v => (v && v.length >= 20) || '文章内容至少20个字符'
        ]
      },
      form: {
        title: '',
        content: ''
      },
      isEdit: false,
      published: false,
      blogId: router.query.id || null,
    }
  },
  async created() {
    if (this.blogId) {
      this.isEdit = true
      await this.fetchBlogDetail()
    }
  },
  methods: {
    async fetchBlogDetail() {
      try {
        const blogStore = useBlogStore()
        const blog = await blogStore.editBlog(this.blogId)
        this.form.title = blog.title
        this.form.content = blog.content
        this.published = blog.published
        
      } catch (error) {
        message.error('获取博客详情失败')
      }
    },
    handleContentChange(e) {
      try {
        this.form.content = e.target.value
      } catch (error) {
        console.error('Error handling content change:', error)
      }
    },
    async submitForm() {
      try {
        const valid = await this.$refs.formRef.validate()
        if (!valid) return
        // 检查表单内容是否为空
        if (!this.form.title || !this.form.content) {
          message.warning('请输入标题和内容')
          return
        }
        const blogStore = useBlogStore()
        let result = await blogStore.createBlog(this.blogId,this.form.title, this.form.content, true)
        if (result && result.success) {
          message.success('文章发表成功！')
          this.$router.push({ path: '/profile', query: { tab: 'blogs', email: this.userStats.email } })
        } else {
          message.error(result.message || '发表失败')
        }
      } catch (error) {
        console.error(error)
        message.error(error || '发表文章失败')
      }
    },
    async saveDraft() {
      try {
        if (!this.form.title && !this.form.content) {
          message.warning('没有内容可保存')
          return
        }
        const blogStore = useBlogStore()
        let result = await blogStore.createBlog(this.blogId,this.form.title, this.form.content, false)
        if (result && result.success) {
          message.success('草稿保存成功')
          this.$router.push({ path: '/profile', query: { tab: 'blogs', email: this.userStats.email } })
        } else {
          message.error(result.message || '保存草稿失败')
        }
      } catch (error) {
        message.error(error.message || '保存草稿失败')
      }
    },
    resetForm() {
      this.$refs.formRef.resetFields()
    }
  }
}
</script>

<style scoped>
.create-blog {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.back-btn {
  margin-bottom: 20px;
}

h1 {
  margin-bottom: 30px;
  text-align: center;
  color: rgba(0, 0, 0, 0.85);
}

.editor-container {
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  width: 100%;
}

.ant-tabs-nav {
  margin: 0;
}

.ant-form-item {
  margin-bottom: 24px;
}

.ant-input, .ant-input-textarea {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.preview-area {
  padding: 15px;
  min-height: 500px;
  overflow-y: auto;
  box-sizing: border-box;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
}

.ant-btn {
  margin-right: 8px;
}
</style>
